/*
 * @Author: huangyq
 * @Date: 2022-04-22 16:51:11
 * @LastEditTime: 2022-04-24 17:20:45
 * @LastEditors: huangyq
 * @Description: 用户信息
 * @FilePath: /vue3-boilerplate-pc-client/src/stores/user.ts
 */
import { UserApi } from '@/apis'
import { defineStore, acceptHMRUpdate } from 'pinia'
import { LocationQueryRaw, RouteParamsRaw } from 'vue-router'
import { useLocalStorage } from '@/hooks'

interface IUserState {
  name: string
  phone: string
  records: IRecordItem[]
}

export interface IRecordItem {
  title: string
  name: string
  lastViewTime: number
  params: RouteParamsRaw
  query: LocationQueryRaw
}

const cacheLately = useLocalStorage('cacheLately', {})

export const useUserStore = defineStore('user', {
  state: (): IUserState => {
    return {
      name: '',
      phone: '',
      records: getRecords()
    }
  },
  actions: {
    /**
     * 获取用户信息
     */
    async fetchUserInfo() {
      const res = await UserApi.queryLoginUserUsingGET({})
      if (res.data.success) {
        this.name = (res.data.name as string) || ''
        this.phone = (res.data.mobilePhone as string) || ''
      }
    },
    /**
     * 设置用户操作记录
     */
    setRecords(record: IRecordItem) {
      if (cacheLately.value[record.name]) {
        cacheLately.value[record.name].lastViewTime = Date.now()
      } else {
        cacheLately.value[record.name] = record
      }
      this.records = getRecords()
    }
  }
})

function getRecords() {
  const list = []
  for (const key in cacheLately.value) {
    list.push(cacheLately.value[key])
  }
  return list.sort((a, b) => b.lastViewTime - a.lastViewTime)
}

// hmr
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot))
}
